package matt.design;

import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class TasksDataSource {

	private SQLiteDatabase database;
	private TasksSQLiteHelper dbHelper;
	private String[] allColumns = { TasksSQLiteHelper.COLUMN_ID, TasksSQLiteHelper.COLUMN_USER, 
			TasksSQLiteHelper.COLUMN_NAME, TasksSQLiteHelper.COLUMN_DESC, TasksSQLiteHelper.COLUMN_DUE, 
			TasksSQLiteHelper.COLUMN_START, TasksSQLiteHelper.COLUMN_PRIORITY, TasksSQLiteHelper.COLUMN_GROUP,
			TasksSQLiteHelper.COLUMN_REC, TasksSQLiteHelper.COLUMN_COMP, TasksSQLiteHelper.COLUMN_ADDRESS,
			TasksSQLiteHelper.COLUMN_LATITUDE, TasksSQLiteHelper.COLUMN_LONGITUDE};
	
	/**
	 * gets an instance of the helper class
	 * @param context
	 */
	public TasksDataSource(Context context) {
		dbHelper = new TasksSQLiteHelper(context);
	}
	
	/**
	 * gets the usable database
	 * @throws SQLException
	 */
	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}
	
	/**
	 * closes the database
	 */
	public void close() {
		dbHelper.close();
	}
	
	/**
	 * Adds and item to the database
	 * @param name
	 * @param desc
	 * @param dueDate
	 * @param startDate
	 * @param priority
	 * @param group
	 * @param recurring
	 * @param completed
	 * @return
	 * @throws ParseException
	 */
	public Item createTask(String name, String desc, String dueDate, String startDate,
			int priority, String group, String recurring, boolean completed, String address, String latt, String longi) throws ParseException {
		ContentValues values = new ContentValues();
		values.put(TasksSQLiteHelper.COLUMN_USER, HomepageActivity.CURRENT_USER);
		values.put(TasksSQLiteHelper.COLUMN_NAME, name);
		values.put(TasksSQLiteHelper.COLUMN_DESC, desc);
		values.put(TasksSQLiteHelper.COLUMN_DUE, dueDate);
		values.put(TasksSQLiteHelper.COLUMN_START, startDate);
		values.put(TasksSQLiteHelper.COLUMN_PRIORITY, priority);
		values.put(TasksSQLiteHelper.COLUMN_GROUP, group);
		values.put(TasksSQLiteHelper.COLUMN_REC, recurring);
		values.put(TasksSQLiteHelper.COLUMN_COMP, completed);
		values.put(TasksSQLiteHelper.COLUMN_ADDRESS, address);
		values.put(TasksSQLiteHelper.COLUMN_LATITUDE, latt);
		values.put(TasksSQLiteHelper.COLUMN_LONGITUDE, longi);
		long insertId = database.insert(TasksSQLiteHelper.TABLE_TASKS, null, values);
		Cursor cursor = database.query(TasksSQLiteHelper.TABLE_TASKS,
				allColumns, TasksSQLiteHelper.COLUMN_ID + " = " + insertId, null,
				null, null, null);
		cursor.moveToFirst();
		return cursorToItem(cursor);
	}
	
	public void updateTask(Item task) {
		long id = task.getId();
		System.out.println("Task updated with id: " + id);
		ContentValues values = new ContentValues();
		String user = HomepageActivity.CURRENT_USER;
		values.put(TasksSQLiteHelper.COLUMN_USER, user);
		values.put(TasksSQLiteHelper.COLUMN_NAME, task.getItemName());
		values.put(TasksSQLiteHelper.COLUMN_DESC, task.getDesc());
		values.put(TasksSQLiteHelper.COLUMN_DUE, task.getDueDate());
		values.put(TasksSQLiteHelper.COLUMN_START, task.getStartDate());
		values.put(TasksSQLiteHelper.COLUMN_PRIORITY, task.getPriority());
		values.put(TasksSQLiteHelper.COLUMN_GROUP, task.getItemGroup().getName());
		values.put(TasksSQLiteHelper.COLUMN_REC, task.getRecurring());
		values.put(TasksSQLiteHelper.COLUMN_COMP, task.getCompleted());
		values.put(TasksSQLiteHelper.COLUMN_ADDRESS, task.getAddress());
		values.put(TasksSQLiteHelper.COLUMN_LATITUDE, task.getLatitude());
		values.put(TasksSQLiteHelper.COLUMN_LONGITUDE, task.getLongitude());
		database.update(TasksSQLiteHelper.TABLE_TASKS, values, 
				TasksSQLiteHelper.COLUMN_ID + " = ? AND " + 
				TasksSQLiteHelper.COLUMN_USER + " = ?", new String[] { ""+id, user });
	}
	
	/**
	 * Deletes an item from the database
	 * @param task
	 */
	public void deleteTask(Item task) {
		long id = task.getId();
		database.delete(TasksSQLiteHelper.TABLE_TASKS, TasksSQLiteHelper.COLUMN_ID
				+ " = ? AND " + TasksSQLiteHelper.COLUMN_USER 
				+ " = ?", new String[] { ""+id, HomepageActivity.CURRENT_USER });
	}
	

	/**
	 * gets a cursor that parses all items
	 * @param user
	 * @return
	 * @throws ParseException
	 */
	public List<Item> getAllItems(String user) throws ParseException {
		List<Item> items = new ArrayList<Item>();
		Cursor cursor = dbHelper.getReadableDatabase().
				rawQuery("SELECT *"
						+ " FROM " + TasksSQLiteHelper.TABLE_TASKS
						+ " WHERE " + TasksSQLiteHelper.COLUMN_USER + " = ?", new String[] { user });
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Item item = cursorToItem(cursor);
			items.add(item);
			cursor.moveToNext();
		}
		return items;
	}
	
	public List<Item> getAllCompletedItems(String user) throws ParseException {
		List<Item> items = new ArrayList<Item>();
		Cursor cursor = dbHelper.getReadableDatabase().
				rawQuery("SELECT *"
						+ " FROM " + TasksSQLiteHelper.TABLE_TASKS
						+ " WHERE " + TasksSQLiteHelper.COLUMN_USER + " = ?"
						+ " AND " + TasksSQLiteHelper.COLUMN_COMP + " = ?"
						+ " ORDER BY " + TasksSQLiteHelper.COLUMN_DUE, new String[] { user, "1" });
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Item item = cursorToItem(cursor);
			items.add(item);
			cursor.moveToNext();
		}
		return items;
	}
	public List<Item> getAllUncompletedItems(String user) throws ParseException {
		List<Item> items = new ArrayList<Item>();
		Cursor cursor = dbHelper.getReadableDatabase().
				rawQuery("SELECT *"
						+ " FROM " + TasksSQLiteHelper.TABLE_TASKS
						+ " WHERE " + TasksSQLiteHelper.COLUMN_USER + " = ?"
						+ " AND " + TasksSQLiteHelper.COLUMN_COMP + " = ?"
						+ " ORDER BY " + TasksSQLiteHelper.COLUMN_DUE, new String[] { user, "0" });
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Item item = cursorToItem(cursor);
			items.add(item);
			cursor.moveToNext();
		}
		return items;
	}
	
	public List<Item> getAllPastDate(String user, String date) throws ParseException {
		List<Item> items = new ArrayList<Item>();
		Cursor cursor = dbHelper.getReadableDatabase().
				rawQuery("SELECT *"
						+ " FROM " + TasksSQLiteHelper.TABLE_TASKS
						+ " WHERE " + TasksSQLiteHelper.COLUMN_USER + " = ?"
						+ " AND " + TasksSQLiteHelper.COLUMN_DUE + " >= ?"
						+ " ORDER BY " + TasksSQLiteHelper.COLUMN_DUE, new String[] { user, date });
		cursor.moveToFirst();
		while(!cursor.isAfterLast()){
			Item item = cursorToItem(cursor);
			items.add(item);
			cursor.moveToNext();
		}
		return items;
	}
	
	public List<Item> getAllOfGroup(String user, String group) throws ParseException {
		List<Item> items = new ArrayList<Item>();
		Cursor cursor = dbHelper.getReadableDatabase().
				rawQuery("SELECT *"
						+ " FROM " + TasksSQLiteHelper.TABLE_TASKS
						+ " WHERE " + TasksSQLiteHelper.COLUMN_USER + " = ?"
						+ " AND " + TasksSQLiteHelper.COLUMN_GROUP + " = ?"
						+ " ORDER BY " + TasksSQLiteHelper.COLUMN_DUE, new String[] { user, group});
		cursor.moveToFirst();
		while(!cursor.isAfterLast()){
			Item item = cursorToItem(cursor);
			items.add(item);
			cursor.moveToNext();
		}
		return items;
	}
	
	/**
	 * Gets all of the groups
	 * @return
	 */
	public List<Group> getAllGroups() {
		List<Group> groups = new ArrayList<Group>();
		Cursor cursor = dbHelper.getReadableDatabase().
				rawQuery("SELECT DISTINCT " + TasksSQLiteHelper.COLUMN_GROUP
						+ " FROM " + TasksSQLiteHelper.TABLE_TASKS, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Group group = cursorToGroup(cursor);
			groups.add(group);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return groups;
	}
	
	/**
	 * Takes in a cursor and then sets all of its fields
	 * @param cursor
	 * @return
	 * @throws ParseException
	 */
	private Item cursorToItem(Cursor cursor) throws ParseException {
		Item item = new Item(cursor.getLong(0));
		item.setItemName(cursor.getString(2));
		item.setDesc(cursor.getString(3));
		
		//THIS IS WHERE THE ERROR IS vvv
		
		String dueDate = cursor.getString(4);
		String startDate = cursor.getString(5);
		item.setDueDate(dueDate);
		item.setStartDate(startDate);
		
		item.setPriority(cursor.getInt(6));
		item.setItemGroup(new Group(cursor.getString(7)));
		
		String recurring = cursor.getString(8);
		item.setRecurring(recurring);
		
		boolean comp = (cursor.getInt(9) == 0) ? false : true;
		item.setCompleted(comp);
		
		String address = cursor.getString(10);
		String latitude = cursor.getString(11);
		String longitude = cursor.getString(12);
		item.setAddress(address);
		item.setLatitude(latitude);
		item.setLongitude(longitude);
		
		return item;
	}
	
	/**
	 * Takes in a cursor and then creates a new group
	 * @param cursor
	 * @return
	 */
	private Group cursorToGroup(Cursor cursor) {
		Group group = new Group();
		group.setName(cursor.getString(0));
		return group;
	}
}
